package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.Log;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.*;

@Service
public class LogApiImpl implements LogApi{

    @Autowired
    private MongoTemplate mongoTemplate;




    /**
     * 查询用户登录地点
     * @param userId 用户id
     * @return
     */
    @Override
    public String queryUserLocation(Long userId) {
        //通过用户id查询用户登录地点
        Query query = Query.query(Criteria.where("userId").is(userId));
        Map<String,String> map = mongoTemplate.findOne(query, Map.class, "user_location");
        if (ObjectUtil.isNotEmpty(map)){
            String address = map.get("address");
            return address;
        }
        return null;
    }

    /**
     * 查询最近登录时间
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public Long queryUserLogTime(Long userId) {
        //通过用户id查询用户Log对象
        Query query = Query.query(Criteria.where("userId").is(userId).and("logType").is("01")).with(Sort.by(Sort.Order.desc("logTime"))).limit(1);
        Log log = mongoTemplate.findOne(query, Log.class);
        return log.getLogTime();
    }

    /**
     * 保存用户登录日志
     * @return
     */
    @Override
    public boolean saveLog(Log log) {
        //通过MongoDB保存日志信息
        Log save = mongoTemplate.save(log);
        if (ObjectUtil.isNotEmpty(save)){
            return true;
        }
        return false;
    }

    /**
     * 查询日志翻页
     * @param page 当前页
     * @param pagesize 每页显示数
     * @param UserId 发布动态的用户id
     * @param sortProp 排序字段
     * @param sortOrder sortOrder ascending 升序 descending 降序
     * @return
     */
    @Override
    public List<Log> queryLog(Integer page, Integer pagesize, Long UserId, String sortProp, String sortOrder) {
        //创建集合存储数据
        List<Log> logList = new ArrayList<>();
        //如果排序字段和排序规则不为空,按照条件查询
        if (StrUtil.isNotEmpty(sortProp) && StrUtil.isNotEmpty(sortOrder))
            //按照字段,升序查询
            if (sortOrder.equals("ascending")) {
                PageRequest pageRequest = PageRequest.of(page - 1, pagesize, Sort.by(Sort.Order.asc(sortProp)));
                Query query = Query.query(Criteria.where("userId").is(UserId).and("logType").is("01")).with(pageRequest);
                logList = mongoTemplate.find(query, Log.class);
            } else {
                //按照字段,降序查询
                if (sortOrder.equals("descending")) {
                    PageRequest pageRequest = PageRequest.of(page - 1, pagesize, Sort.by(Sort.Order.desc(sortProp)));
                    Query query = Query.query(Criteria.where("userId").is(UserId).and("logType").is("01")).with(pageRequest);
                    logList = mongoTemplate.find(query, Log.class);
                }
            }
        else {
            //不进行排序查询
            PageRequest pageRequest = PageRequest.of(page - 1, pagesize);
            Query query = Query.query(Criteria.where("userId").is(UserId).and("logType").is("01")).with(pageRequest);
            logList = mongoTemplate.find(query, Log.class);
        }

        //返回数据
        return logList;
    }

    /**
     * 查询今日登录次数
     * @param zeroTime 今天0时
     * @param nowTime 当前系统时间
     * @return
     */
    @Override
    public Long queryLoginTimesToday(long zeroTime, long nowTime) {
        Query query = Query.query(Criteria.where("logTime").lte(nowTime).gte(zeroTime).and("logType").is("01"));
        return mongoTemplate.count(query, Log.class);
    }

    /**
     * 查询昨日登录次数
     * @param zeroTime 今天0时
     * @param dayTime  昨日0时
     * @return
     */
    @Override
    public Long queryYesterday(long zeroTime, long dayTime) {
        Query query = Query.query(Criteria.where("logTime").lte(zeroTime).gte(dayTime).and("logType").is("01"));
        return mongoTemplate.count(query, Log.class);
    }

    /**
     * 今日活跃用户数
     * @param zeroTime 今日0时
     * @param nowTime  当前系统时间
     * @return
     */
    @Override
    public Long queryActiveUsersToday(long zeroTime, long nowTime) {
        Query query=Query.query(Criteria.where("logTime").lte(nowTime).gte(zeroTime).and("logType").is("01"));
        List<Log> logList = mongoTemplate.find(query, Log.class);
        List<Object> userIdList = CollUtil.getFieldValues(logList, "userId");
        //去重复
        Set<Object> set = new HashSet<>();
        for (Object o : userIdList) {
            set.add(o);
        }
        return Convert.toLong(set.size());
    }

    /**
     * 昨日活跃用户
     * @param zeroTime 今日0时
     * @param dayTime 昨日0时
     * @return
     */
    @Override
    public Long queryYesterdayUsersToday(long zeroTime, long dayTime) {
        Query query = Query.query(Criteria.where("logTime").lte(zeroTime).gte(dayTime).and("logType").is("01"));
        List<Log> logList = mongoTemplate.find(query, Log.class);
        List<Object> userIdList = CollUtil.getFieldValues(logList, "userId");
        //去重复
        Set<Object> set = new HashSet<>();
        for (Object o : userIdList) {
            set.add(o);
        }
        return Convert.toLong(set.size());
    }

    /**
     * 昨日活跃用户
     * @param yesterdayDayTime 前日0时
     * @param dayTime 昨日0时
     * @return
     */
    @Override
    public Long queryYesterdayUsersDateTime(long dayTime, long yesterdayDayTime) {
        Query query=Query.query(Criteria.where("logTime").lte(dayTime).gte(yesterdayDayTime).and("logType").is("01"));
        List<Log> logList = mongoTemplate.find(query, Log.class);
        List<Object> userIdList = CollUtil.getFieldValues(logList, "userId");
        //去重复
        Set<Object> set = new HashSet<>();
        for (Object o : userIdList) {
            set.add(o);
        }
        return Convert.toLong(set.size());
    }

    /**
     * 查询所有活跃用户
     * @return
     */
    @Override
    public List<Log> queryActive() {
        Query query = new Query();
       return mongoTemplate.find(query, Log.class);
    }

    /**
     * 查询过去30天活跃用户
     * @param nowTime
     * @param monthTime
     * @return
     */
    @Override
    public Long queryActivePassMonth(long nowTime, long monthTime) {
        Query query=Query.query(Criteria.where("logTime").lte(nowTime).gte(monthTime).and("logType").is("01"));
        List<Log> logList = mongoTemplate.find(query, Log.class);
        List<Object> userIdList = CollUtil.getFieldValues(logList, "userId");
        //去重复
        Set<Object> set = new HashSet<>();
        for (Object o : userIdList) {
            set.add(o);
        }
        return Convert.toLong(set.size());

    }

    /**
     * 查询过去7天活跃用户
     * @param nowTime 当前系统时间
     * @param weekTime 7日前0时
     * @return
     */
    @Override
    public Long queryActivePassWeek(long nowTime, long weekTime) {
        Query query=Query.query(Criteria.where("logTime").lte(nowTime).gte(weekTime).and("logType").is("01"));
        List<Log> logList = mongoTemplate.find(query, Log.class);
        List<Object> userIdList = CollUtil.getFieldValues(logList, "userId");
        //去重复
        Set<Object> set = new HashSet<>();
        for (Object o : userIdList) {
            set.add(o);
        }
        return Convert.toLong(set.size());
    }

    /**
     * 查询过去7天所有用户登录记录
     * @param zeroTime
     * @param weekTime
     * @return
     */
    @Override
    public List<Log> queryUser(long zeroTime, long weekTime) {
        Query query = Query.query(Criteria.where("logType").is("01").and("logTime").lte(zeroTime).gte(weekTime)).with(Sort.by(Sort.Order.desc("logTime")));
        List<Log> logList = mongoTemplate.find(query, Log.class);
        return logList;
    }

    /**
     * 查询当前用户登录次数
     * @param userId
     * @param newTime
     * @param endTime
     * @return
     */
    @Override
    public Long queryUserConut(Long userId, long newTime, long endTime) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("logType").is("01").and("logTime").lt(endTime).gt(newTime));
        return mongoTemplate.count(query, Log.class);

    }

    /**
     * 查询指定时间段活跃用户数
     * @param ed
     * @param sd
     * @return
     */
    @Override
    public Long queryActiveUserCount(Long sd, Long ed) {
        //添加查询条件
        Query query = Query.query(Criteria.where("logTime").lt(ed).gt(sd).and("logType").is("01"));
        List<Log> logList = mongoTemplate.find(query, Log.class);
        List<Object> userIdList = CollUtil.getFieldValues(logList, "userId");
        //去重复
        Set<Object> set = new HashSet<>();
        for (Object o : userIdList) {
            set.add(o);
        }
        return Convert.toLong(set.size());
    }

    /**
     * 查询指定时间段的用户
     * @param sd
     * @param ed
     * @return
     */
    @Override
    public List<Log> queryNextDayLeft(long sd, long ed) {
        Query query = Query.query(Criteria.where("logTime").lt(ed).gt(sd).and("logType").is("01"));
        return  mongoTemplate.find(query, Log.class);

    }


}
